/*!
 * Copyright (c) 2023-present StarDreamNet
 */
(document.loader || (document.loader = [])).push(["post", class {
    constructor() {
        this.postId = location.pathname.split("post/")[1];
        this.postData = null;
        this.talkData = null;
        this.userData = null;
        this.editor = null;
    };

    init_(require) { // 全局初始化
        const { resize, dateSpanString, renderNameAndGroups } = require("index");

        this.resize = resize;
        this.dateSpanString = dateSpanString;
        this.renderNameAndGroups = renderNameAndGroups;

        this.loadAll();
    }
    loadAll() {
        $(".app-main-content").append($(`<div class="app-post"></div>`));
        this.getPostData().then(() => {
            this.getTalksData();
        })
    };

    // —————————————————————————— 帖子信息&内容 ——————————————————————————
    loadPostStart() {
        $(".app-post").attr("load", "").append($("<p class='load'>加载中</p>"));
        this.resize();
    };
    loadPostEnd() {
        $(".app-post").removeAttr("load", "").find("p.load").remove();
        this.resize();
    };
    loadPostError(msg) {
        this.loadPostEnd();
        $(".app-post").attr("load", "").attr("error", "").append($("<p>").text(msg || '加载出错'));
        this.resize();
    };
    renderPostContent() {
        var data = this.postData;
        var user = this.userData;
        var post = $('.app-post');
        var title = $('<div class="app-post-title"></div>');
        var titleUp = $('<div class="app-post-title-up">置</div>');
        var titleBest = $('<div class="app-post-title-best">精</div>');
        var titleHot = $('<div class="app-post-title-hot">热</div>');
        var titleContent = $('<p></p>');
        var info = $('<div class="app-post-info"></div>');

        var sender = $('<div class="app-post-sender"></div>');
        var senderImg = $('<img class="app-post-sender-img" width="50" height="50">');
        var senderInfo = $('<div class="app-post-sender-info"><p></p></div>');

        var content = $('<div class="app-post-content" id="test-editormd"></div>');
        var talk = $('<div class="app-post-talk"></div>');
        var talkt = $('<div class="app-post-talkt"></div>');
        var talktStar = $('<div class="app-post-talkt-star"></div>');
        var talktStarImg = $('<img>');
        var talktInput = $('<textarea class="app-post-talkt-input"></textarea>');
        var talktSend = $('<button class="app-post-talkt-send" disabled>发送</button>');
        var talkh = $('<div class="app-post-talkh">评论</div>');
        var talks = $('<div class="app-post-talks"></div>');
        post.append(title, info, sender, content, talk);
        sender.append(senderImg, senderInfo);
        talk.append(talkt, talkh, talks);
        talktStar.append(talktStarImg);
        talkt.append(talktStar, talktInput, talktSend);
        title.append(titleContent);
        senderImg.attr("src", user.img);
        senderImg.attr("alt", user.name);
        talktStarImg.attr("src", data.is_goods ? "/static/image/star.svg" : "/static/image/unstar.svg");
        talktStarImg.attr("alt", "点赞");

        this.renderNameAndGroups(user.name, user.group || [], "/user/" + user.id)
            .insertBefore(senderInfo.children().first());

        senderInfo.find("p").text(this.dateSpanString(data.time * 1000, Date.now()));
        title.text(data.title);
        if (data.is_on) title.append(titleUp);
        if (data.is_best) title.append(titleBest);
        if (data.is_hot) title.append(titleHot);
        info.text(`访问：${data.views} 点赞：${data.goods}`);

        talktInput.on("input", () => {
            talktInput.css('cssText', "");
            talktSend.prop("disabled", !(talktInput.val().length));
            talktInput.css('height', talktInput.prop("scrollHeight"));
        });

        talktSend.on("click", () => {
            talktSend.prop("disabled", true);
            talktInput.prop("disabled", true);
            this.sendTalk(talktInput.val()).then(r => {
                talktSend.prop("disabled", false);
                talktInput.prop("disabled", false);
                if (r) {
                    talktSend.prop("disabled", true);
                    talktInput.val("");
                }
            })
        });

        talktStar.on("click", () => {
            if (talktStar.prop("disabled")) return;
            talktStar.prop("disabled", true);
            this[(talktStarImg.attr("src").includes("/star") ? "unG" : "g") + "ood"]().then(v => {
                talktStar.prop("disabled", false);
                if (v) {
                    if (talktStarImg.attr("src").includes("/star")) data.goods--;
                    else data.goods++;
                    info.text(`访问：${data.views} 点赞：${data.goods}`);
                    talktStarImg.attr("src", talktStarImg.attr("src").includes("/star") ? "/static/image/unstar.svg" : "/static/image/star.svg");
                }
            })
        });

        this.editor = editormd.markdownToHTML("test-editormd", {
            markdown: this.postData.text,
            path: "/static/editormd/lib/",
            htmlDecode: false,
            emoji: true,
            toc: true,
            tocm: true,
            taskList: true,
            tex: true,
            flowChart: true,
            sequenceDiagram: true,
        });

        var titleShare = $('<div class="app-post-title-share"><img src="/static/image/share.svg" alt="分享"></div>');
        titleShare.on("click", () => {
            this.shareDialog();
        });

        title.append(titleShare);

        this.resize();
    };
    getPostData() {
        $(".app-post").html("");
        return new Promise((resolve, reject) => {
            this.loadPostStart();

            $.ajax('/api/shequ/get_post/' + this.postId + "?t=" + Date.now(), {
                contentType: 'application/json',
            }).done((response) => {
                if (response.code == 200) {
                    this.postData = response.data;

                    $.ajax('/api/shequ/get_user/' + response.data.user_id + "?t=" + Date.now(), {
                        contentType: 'application/json',
                    }).done((response) => {
                        if (response.code == 200) {
                            this.userData = response.data;

                            this.loadPostEnd();
                            this.renderPostContent();

                            resolve();
                        } else {
                            this.loadPostError(response.msg);
                            reject(response.msg);
                        }
                    }).fail((error) => {
                        this.loadPostError(error);
                        reject(error);
                    });
                } else {
                    this.loadPostError(response.msg);
                    reject(response.msg);
                }
            }).fail((error) => {
                this.loadPostError(error);
                reject(error);
            });
        });
    };

    // —————————————————————————— 分享 ——————————————————————————
    async copyText(text) {
        try {
            await navigator.clipboard.writeText(text);
            return true;
        } catch (e) {
            var i = document.createElement("textarea");
            i.style.fontSize = "12pt";
            i.style.border = "0";
            i.style.padding = "0";
            i.style.margin = "0";
            i.style.position = "absolute";
            i.style.left = "-9999px";
            i.value = text;
            document.body.appendChild(i);
            i.setAttribute("readonly", "");
            if (i.focus) i.focus();
            i.select();
            i.setSelectionRange(0, text.length);
            try {
                document.execCommand('copy');
                document.body.removeChild(i);
                return true;
            } catch (e) {
                document.body.removeChild(i);
                return false;
            }
        }
    };
    shareURL(href) {
        const img = $(".app-post-content img").first().attr('src') || '';
        const title = document.title;
        const url = location.href;
        const content_ = $(".app-post-content").text();
        const content = content_.length > 80 ? content_.substring(0, 80) + '...' : content_;

        return href.replaceAll('{{img}}', encodeURIComponent(img))
            .replaceAll('{{title}}', encodeURIComponent(title))
            .replaceAll('{{content}}', encodeURIComponent(content))
            .replaceAll('{{url}}', encodeURIComponent(url));
    }
    shareDialog() {
        // 填写格式："图标":"链接"
        const otherShare = {
            // QQ空间
            "https://qzone.qq.com/favicon.ico":
                "https://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?pics={{img}}&summary={{content}}&title={{title}}&url={{url}}",

            // QQ好友
            "https://connect.qq.com/favicon.ico":
                "https://connect.qq.com/widget/shareqq/index.html?pics={{img}}&summary={{content}}&title={{title}}&url={{url}}",

            // 微博
            "https://weibo.com/favicon.ico":
                "https://service.weibo.com/share/share.php?pic={{img}}&title={{title}}&url={{url}}"
        }

        const main = $('<div class="app-share">');

        // 二维码，用于微信分享
        const qrcode = $('<div class="app-share-qrcode">');
        const wechat = $('<p>打开微信“扫一扫”即可将网页分享至朋友圈</p>');
        new QRCode(qrcode[0], {
            text: location.href,
            width: 128,
            height: 128,
            colorDark: "#000000",
            colorLight: "#ffffff",
            correctLevel: QRCode.CorrectLevel.H
        });

        // 显示链接
        const url = $('<div class="app-share-url">');
        const urlText = $('<div class="app-share-url-text">');
        const urlCopy = $('<div class="app-share-url-copy">');
        url.append(urlText, urlCopy);

        urlText.text(location.href);
        urlCopy.on("click", () => {
            this.copyText(location.href).then(() => {
                dsnackbar('success', '复制成功')
            }).catch(() => {
                dsnackbar('error', '复制出错')
            })
        });

        // 其他分享方式
        const other = $('<div class="app-share-other">');
        for (let key in otherShare) {
            let item = $('<a class="app-share-other-item">');
            let img = $('<img>');
            item.append(img);
            other.append(item);

            img.attr("src", key);
            item.attr("href", this.shareURL(otherShare[key]));
            item.attr("target", "_blank");
        }

        main.append(qrcode, wechat, url, other);

        swal({
            button: false,
        });
        $('.swal-modal').append(main);
    }

    // —————————————————————————— 评论&回复 ——————————————————————————
    loadTalksStart() {
        $(".app-post-talks").attr("load", "").append($("<p class='load'>加载中</p>"));
        this.resize();
    };
    loadTalksEnd() {
        $(".app-post-talks").removeAttr("load", "").find("p.load").remove();
        this.resize();
    };
    loadTalkError(msg) {
        this.loadTalksEnd();
        $(".app-post-talk").attr("error", "").append($("<p>").text(msg || '加载出错'));
        this.resize();
    };
    renderReply(talk2) {
        let item = $('<div class="app-post-talks-item-main-reply-item"></div>');
        let avatar = $('<div class="app-post-talks-item-main-reply-item-avatar"><img width="50" height="50"></div>');
        let main = $('<div class="app-post-talks-item-main-reply-item-main"></div>');
        let text = $('<div class="app-post-talks-item-main-reply-item-main-text"></div>');
        let name = $('<a></a>');
        let colon = $('<span>:</span>');
        let content = $('<p></p>');
        let time = $('<div class="app-post-talks-item-main-reply-item-main-time"></div>');
        item.append(avatar, main);
        main.append(text, time);
        text.append(name, colon, content);
        name.text(talk2.name);
        name.attr("href", "/user/" + talk2.user_id);
        content.text(talk2.text);
        time.text(this.dateSpanString(talk2.time * 1000, Date.now()));
        avatar.find("img").attr("src", talk2.img);
        avatar.find("img").attr("alt", talk2.name);
        return item;
    };
    renderTalk(talk) {
        let item = $('<div class="app-post-talks-item"></div>');
        let avatar = $('<div class="app-post-talks-item-avatar"><img width="50" height="50"></div>');
        let main = $('<div class="app-post-talks-item-main"></div>');
        let name = this.renderNameAndGroups(talk.name, talk.user_group || [], "/user/" + talk.user_id)
        let content = $('<div class="app-post-talks-item-main-content"></div>');
        let info = $('<div class="app-post-talks-item-main-info"></div>');
        let reply = $('<div class="app-post-talks-item-main-reply"></div>');

        var openReplyInput = $('<div class="app-post-talks-openreply"></div>');
        var talkt = $('<div class="app-post-talkt"></div>');
        var talktInput = $('<textarea class="app-post-talkt-input"></textarea>');
        var talktSend = $('<button class="app-post-talkt-send" disabled>发送</button>');

        openReplyInput.text(`添加回复`);

        talkt.append(talktInput, talktSend);
        talkt.hide();

        item.append(avatar, main);
        main.append(name, content, info, openReplyInput, talkt, reply);

        content.text(talk.text);

        $('<span class="app-post-talks-item-main-info-time">').text(this.dateSpanString(talk.time * 1000, Date.now())).appendTo(info);
        info.append(openReplyInput);

        avatar.find("img").attr("src", talk.img);
        avatar.find("img").attr("alt", talk.name);
        for (let talk2 of talk.talks) {
            reply.append(this.renderReply(talk2));
        }

        openReplyInput.on("click", () => {
            talkt.toggle();
        });

        talktInput.on("input", () => {
            talktInput.css('cssText', "");
            talktSend.prop("disabled", !(talktInput.val().length));
            talktInput.css('height', talktInput.prop("scrollHeight"));
        });

        talktSend.on("click", () => {
            talktSend.prop("disabled", true);
            talktInput.prop("disabled", true);
            this.sendReply(talk.id, talktInput.val()).then(result => {
                talktSend.prop("disabled", false);
                talktInput.prop("disabled", false);
                if (result) {
                    talktSend.prop("disabled", true);
                    talktInput.val("");

                    if (!reply.children().length) {
                        reply.append(this.renderReply(result));
                    } else {
                        this.renderReply(result).insertBefore(reply.children().first());
                    }
                }
            })
        });

        return item;
    };
    renderTalks() {
        var data = this.talkData;
        for (let talk of data)
            $(".app-post-talks").append(this.renderTalk(talk));
        if (!data.length) {
            $(".app-post-talks").attr("load", "").append($("<p>暂无评论</p>"));
        }
        this.resize();
    };
    getTalksData() {
        $(".app-post-talks").html("");
        return new Promise((resolve, reject) => {
            this.loadTalksStart();
            $.ajax('/api/shequ/get_talk/' + this.postId + "?t=" + Date.now(), {
                contentType: 'application/json',
            }).done((response) => {
                if (response.code == 200) {
                    var talkData = response.data;
                    this.talkData = talkData;
                    this.loadTalksEnd();
                    this.renderTalks();
                    resolve();
                } else {
                    this.loadTalkError(response.msg);
                    reject(response.msg);
                }
            }).fail((error) => {
                this.loadTalkError(error);
                reject(error);
            });
        });
    };

    // —————————————————————————— 一些方法 ——————————————————————————
    sendTalk(value) { // 发送评论
        return new Promise(resolve => {
            const data = {
                text: value,
                post_id: this.postId
            };

            fetch('/api/shequ/send_talk/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(data)
            }).then(response => response.json())
                .then(result => {
                    if (result.code == 200) {
                        resolve(true);
                        if (!$(".app-post-talks-item").length) {
                            $(".app-post-talks p").remove();
                            this.renderTalk(result.data).appendTo($(".app-post-talks"));
                        } else {
                            this.renderTalk(result.data).insertBefore($(".app-post-talks-item").first());
                        }
                    } else {
                        dsnackbar('error', result.msg);
                        resolve(false)
                    }
                })
                .catch(() => {
                    dsnackbar('error', '请稍后再试');
                    resolve(false)
                });
        })
    };
    sendReply(talk_id, value) { // 发送回复
        return new Promise(resolve => {
            const data = {
                text: value,
                talk_id: String(talk_id)
            };

            fetch('/api/shequ/send_talk/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(data)
            }).then(response => response.json())
                .then(result => {
                    if (result.code == 200) {
                        resolve(result.data);
                    } else {
                        dsnackbar('error', result.msg);
                        resolve(null)
                    }
                })
                .catch(() => {
                    dsnackbar('error', '请稍后再试');
                    resolve(null)
                });
        })
    };
    good() { // 点赞
        return new Promise(resolve => {
            $.ajax(`/api/shequ/setgoods/${this.postId}`, {
                contentType: 'application/json',
            }).done(function (response) {
                if (response.code == 200) {
                    resolve(true);
                } else {
                    dsnackbar('error', response.msg);
                    resolve(false)
                }
            }).fail(function () {
                dsnackbar('error', '请稍后再试');
                resolve(false)
            })
        })
    };
    unGood() { // 取消点赞
        return new Promise(resolve => {
            $.ajax(`/api/shequ/unsetgoods/${this.postId}`, {
                contentType: 'application/json',
            }).done(function (response) {
                if (response.code == 200) {
                    resolve(true)
                } else {
                    dsnackbar('error', response.msg);
                    resolve(false)
                }
            }).fail(function () {
                dsnackbar('error', '请稍后再试');
                resolve(false)
            })
        })
    };
}])